package ewa

import (
	"fmt"
	"time"
	jwt "github.com/dgrijalva/jwt-go"
)

/////////////////////////////////////////////////////////////////////////////////////////////
var (
	// Define a secure key string used
	// as a salt when hashing our tokens.
	// Please make your own way more secure than this,
	// use a randomly generated md5 hash or something.
	JwtSignedString = []byte("ni5ONx13")
)

// jwtCustomClaims are custom claims extending default ones.
type JwtCustomClaims struct {
	Name  string `json:"name"`
	jwt.StandardClaims
}

func JwtTokenCreate(Username string) string {
	// Set custom claims
	claims := &JwtCustomClaims{
		Username,			
		jwt.StandardClaims{	//token 有效期
			ExpiresAt: time.Now().Add(time.Hour * 10).Unix(),
		},
	}
	// Create token with claims
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// Generate encoded token and send it as response.
	t, err := token.SignedString(JwtSignedString)
	if err != nil {
	    l:=fmt.Sprintf("----Echo/> %v", err)
    	Log(l)
		return ""
	}

	return t
}

// Decode a token string into a token object
func JwtTokenDecode(tokenString string) (*JwtCustomClaims, error) {
    // Parse the token
    token, err := jwt.ParseWithClaims(tokenString, &JwtCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return JwtSignedString, nil
    })

    // Validate the token and return the custom claims
    if claims, ok := token.Claims.(*JwtCustomClaims); ok && token.Valid {
        return claims, nil
    } else {
        return nil, err
    }
}